import axios from 'axios'
import qs from 'qs'
const CancelToken = axios.CancelToken
const pending = {}
// create an axios instance
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? 'http://47.99.202.46:11010' : '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

const remotePending = (key, isRequest = false) => {
  if (pending[key] && isRequest) {
    pending[key]('取消重复请求')
  }
  delete pending[key]
}

// request interceptor
service.interceptors.request.use(
  config => {
    const key = config.url + '&' + config.method
    remotePending(key, true)
    config.cancelToken = new CancelToken(c => {
      pending[key] = c
    })
    // do something before request is sent
    if (config.method === 'get') {
      if (config.data) {
        config.url = config.url + '?' + qs.stringify(config.data)
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const key = response.config.url + '&' + response.config.method
    remotePending(key)
    // if the custom code is not 200, it is judged as an error.
    if (response.status !== 200) {
      return Promise.reject(response)
    } else {
      return response.data
    }
  },
  error => {
    console.log('error: ', error)
    return Promise.reject(error)
  }
)

export default service
